// package-signin/pages/edit-product/index.js
const app = getApp();
import { PACKAGE_PRODUCT_PAGE } from '../../../constants/route';
import { navTo, navBack, tipToast } from '../../../common/env';
import { arr2Obj } from '../../../common/utils';

Page({
    data: {
        signinInfo: {},
        checkedList: [],
    },
    onLoad(options) {
        app.event.addListener('sendSigninInfo', this._handleSendSignin.bind(this));
    },
    onUnload() {
        app.event.removeListener('sendSigninInfo');
    },
    _handleSendSignin(signinInfo) {
        const checkedList = signinInfo.activityProductWithSkus.map(i => i.productId);
        this.setData({
            signinInfo,
            checkedList,
        });
    },
    handleNavToCreate() {
        navTo(PACKAGE_PRODUCT_PAGE['productEdit']);
    },
    handleProductChecked(e) {
        const { ids, products } = e.detail;
        const idsMap = arr2Obj(ids);
        let { activityProductWithSkus = [] } = this.data.signinInfo;
        products.forEach(p => {
            const skus = p.productSpecs && p.productSpecs.length ? p.productSpecs.map(s => {
                s.productId = p.productId;
                s.maximum = '';
                s.price = 0;
                s.skuName = s.name;
                return s;
            }) : [{
                productId: p.productId,
                productSpecId: '0',
                price: 0,
                maximum: '',
            }];
            const ps = {
                productId: p.productId,
                productName: p.name,
                productPics: p.pics,
                priceMin: 0,
                priceMax: 0,
                skus: skus,
                isShow: true,
                quantity: 1,
            };
            if (activityProductWithSkus.findIndex(i => i.productId === p.productId) === -1) {
                activityProductWithSkus.push(ps);
            }
        });
        activityProductWithSkus = activityProductWithSkus.filter(p => idsMap[p.productId]);
        this.setData({
            checkedList: ids,
            'signinInfo.activityProductWithSkus': activityProductWithSkus,
        });
    },
    handleSave() {
        const { signinInfo } = this.data;
        if (!signinInfo.activityProductWithSkus || !signinInfo.activityProductWithSkus.length) {
            tipToast('选择实物商品');
            return;
        }
        app.event.trigger('getSigninInfo', signinInfo);
        navBack();
    },
})
